package com.hyf.gateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.util.List;


@Component
public class PostFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "post";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletResponse response = ctx.getResponse();
        int status = response.getStatus();
        response.setHeader("token","123");
        if(status==302){ //重定向
            String rootPath="http://localhost:8080";
            String proxy = ctx.get("proxy").toString();
            List<com.netflix.util.Pair<String, String>> zuulResponseHeaders = ctx.getZuulResponseHeaders();
            for(com.netflix.util.Pair<String, String> pair:zuulResponseHeaders){
                String first = pair.first();
                if("Location".equals(first)){
                    //http://localhost:8080/redirectSuccess
                    String second = pair.second();
                    second=second.replaceFirst(rootPath,rootPath+"/"+proxy);
                    pair.setSecond(second);
                }
            }
            ctx.set("zuulResponseHeaders",zuulResponseHeaders);
        }
        return null;
    }
}
